import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Paper,
  FormControlLabel,
  Switch,
  Divider,
  CircularProgress,
  Tooltip
} from '@mui/material';
import schedulerService from '../services/schedulerService';

const SchedulerManager = () => {
  const [loading, setLoading] = useState(true);
  const [schedulerEnabled, setSchedulerEnabled] = useState(false);
  const [cacheSettings, setCacheSettings] = useState(true);
  const [showSchedulerDesc, setShowSchedulerDesc] = useState(false);
  const [showCacheDesc, setShowCacheDesc] = useState(false);

  // 加载定时器配置
  useEffect(() => {
    const loadSchedulerSettings = async () => {
      try {
        // 初始化定时器服务
        await schedulerService.initialize();
        
        // 获取定时器启用状态
        const enabled = schedulerService.isEnabled();
        setSchedulerEnabled(enabled);
        
        // 获取缓存设置
        const cache = await schedulerService.getCacheSettings();
        setCacheSettings(cache);
        
        setLoading(false);
      } catch (error) {
        console.error('加载定时器配置失败:', error);
        setLoading(false);
      }
    };
    
    loadSchedulerSettings();
  }, []);

  // 处理定时器启用状态变更
  const handleSchedulerEnabledChange = async (event) => {
    const enabled = event.target.checked;
    setSchedulerEnabled(enabled);
    
    try {
      await schedulerService.setEnabled(enabled);
      console.log(`定时器已${enabled ? '启用' : '禁用'}`);
    } catch (error) {
      console.error('更新定时器状态失败:', error);
      // 恢复原状态
      setSchedulerEnabled(!enabled);
    }
  };

  // 处理缓存设置变更
  const handleCacheSettingsChange = async (event) => {
    const cache = event.target.checked;
    setCacheSettings(cache);
    
    try {
      await schedulerService.setCacheSettings(cache);
      console.log(`定时器配置缓存已${cache ? '启用' : '禁用'}`);
    } catch (error) {
      console.error('更新定时器缓存设置失败:', error);
      // 恢复原状态
      setCacheSettings(!cache);
    }
  };

  return (
    <Paper sx={{ p: 3, mb: 3 }}>
      <Typography variant="h7" gutterBottom>
        定时器管理
      </Typography>
      <Divider sx={{ my: 2 }} />
      
      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', p: 2 }}>
          <CircularProgress size={24} />
        </Box>
      ) : (
        <Box>
          <Box 
            onMouseEnter={() => setShowSchedulerDesc(true)}
            onMouseLeave={() => setShowSchedulerDesc(false)}
          >
            <FormControlLabel
              control={
                <Switch
                  checked={schedulerEnabled}
                  onChange={handleSchedulerEnabledChange}
                  color="primary"
                />
              }
              label="启用定时器"
            />
            {showSchedulerDesc && (
              <Typography variant="body2" color="text.secondary" sx={{ mt: 1, mb: 2 }}>
                启用后，系统将定期检查并执行预定的任务，如群发消息和朋友圈发布。
              </Typography>
            )}
          </Box>
          
          <Box 
            onMouseEnter={() => setShowCacheDesc(true)}
            onMouseLeave={() => setShowCacheDesc(false)}
          >
            <FormControlLabel
              control={
                <Switch
                  checked={cacheSettings}
                  onChange={handleCacheSettingsChange}
                  color="primary"
                />
              }
              label="缓存定时器配置"
            />
            {showCacheDesc && (
              <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                启用后，页面刷新时将保留定时器状态设置。禁用则每次刷新页面时重置为默认状态。
              </Typography>
            )}
          </Box>
        </Box>
      )}
    </Paper>
  );
};

export default SchedulerManager;